package xyz.csmcool.imroom.service.impl;

import lombok.RequiredArgsConstructor;
import xyz.csmcool.imroom.entity.Rooms;
import xyz.csmcool.imroom.entity.UserFriend;
import xyz.csmcool.imroom.entity.vo.UserFriendVo;
import xyz.csmcool.imroom.feignclient.ChatClient;
import xyz.csmcool.imroom.feignclient.UserClient;
import xyz.csmcool.imroom.mapper.UserFriendMapper;
import xyz.csmcool.imroom.service.IUserFriendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.csmcool.imutil.ExceptionHandler.CommonException;
import xyz.csmcool.imutil.dto.LastPrivateMessageDto;
import xyz.csmcool.imutil.dto.RoomUserDto;
import xyz.csmcool.imutil.dto.RoomUsersDto;
import xyz.csmcool.imutil.dto.UserDto;
import xyz.csmcool.imutil.webVo.MyPage;
import xyz.csmcool.imutil.webVo.ResultCode;
import xyz.csmcool.imutil.webVo.ResultVo;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author csmcool
 * @since 2022-08-15
 */
@Service
@RequiredArgsConstructor
public class UserFriendServiceImpl extends ServiceImpl<UserFriendMapper, UserFriend> implements IUserFriendService {

    final UserFriendMapper userFriendMapper;
    final UserClient userClient;
    final ChatClient chatClient;
    private static final Integer notPass = 2;

    @Override
    public MyPage<UserDto> getMyFriend(Long page, Long limit, Integer uid) {
        limit = limit < 1 ? 10 : limit;
        page = page < 1 ? 0 : (page - 1) * limit;
        // 查询朋友的ids集合
        List<Integer> integers = userFriendMapper.selectMyFriend(page, limit, uid);
        integers.add(0);

        // 调用接口
        ResultVo<List<UserDto>> roomUserInfo = userClient.getRoomUserInfo(integers);
        if (!roomUserInfo.getSucceed()) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setMessage("获取用户信息失败"));
        }

        List<UserDto> data = roomUserInfo.getData();
        MyPage<UserDto> myPage = new MyPage<>();
        myPage.setContent(data);
        myPage.setTotalElements(userFriendMapper.selectMyFriendCount(uid));
        return myPage;
    }

    @Override
    public MyPage<UserDto> getMyFriendByName(Long page, Long limit, Integer uid, String name) {
        limit = limit < 1 ? 10 : limit;
        page = page < 1 ? 0 : (page - 1) * limit;
        List<Integer> integers = userFriendMapper.selectAllMyFriendId(uid);
        integers.add(0);

        //封装请求数据
        RoomUserDto roomUserDto = new RoomUserDto();
        roomUserDto.setIds(integers);
        roomUserDto.setName(name);
        roomUserDto.setLimit(limit);
        roomUserDto.setPage(page);

        ResultVo<RoomUsersDto> roomUserInfoByName = userClient.getRoomUserInfoByName(roomUserDto);
        if (!roomUserInfoByName.getSucceed()) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setMessage("查询用户失败"));
        }
        RoomUsersDto data = roomUserInfoByName.getData();
        setMessage(data, uid);
        MyPage<UserDto> myPage = new MyPage<>();
        myPage.setTotalElements(data.getTotal());
        myPage.setContent(data.getDtos());
        return myPage;
    }

    /**
     * 是否是朋友*
     *
     * @param uid
     * @param fid
     * @return
     */
    @Override
    public Boolean isFriend(Integer uid, Integer fid) {
        Integer integer = userFriendMapper.selectUserFriend(uid, fid);
        return integer != 0;
    }

    /**
     * 查看添加我为朋友的人
     *
     * @param page
     * @param limit
     * @param uid
     * @return
     */
    @Override
    public MyPage<UserFriendVo> getAddMeFriend(Long page, Long limit, Integer uid) {
        limit = limit < 1 ? 10 : limit;
        page = page < 1 ? 0 : (page - 1) * limit;
        List<UserFriend> userFriends = userFriendMapper.selectAddMe(page, limit, uid);
        MyPage<UserFriendVo> userInfo = getUserInfo(userFriends);
        userInfo.setTotalElements(userFriendMapper.selectAddMeCount(uid));
        return userInfo;
    }

    /**
     * 审核朋友
     *
     * @param uid
     * @param fid
     */
    @Override
    public void examineFriend(Integer uid, Integer fid, Integer isPass) {
        if (isPass == 1 || isPass == 2) {
            Boolean aBoolean = userFriendMapper.addOrUpdateFriend(fid, uid, isPass);
            if (!aBoolean) {
                throw new CommonException(ResultCode.CUSTOM_FAIL.setCode(90231).setMessage("审核朋友失败，请稍后重试"));
            }
        } else {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setCode(90231).setMessage("审核朋友失败，请稍后重试"));
        }

    }

    /**
     * 朋友之间状态
     *
     * @param uid
     * @param fid
     * @return
     */
    @Override
    public Integer selectUserFriendStatus(Integer uid, Integer fid) {
        return userFriendMapper.selectUserIsPass(uid, fid);
    }

    /**
     * 添加好友
     *
     * @param uid
     * @param fid
     * @return
     */
    @Override
    public void addFriend(Integer uid, Integer fid) {
        Integer integer = userFriendMapper.selectUserIsPass(uid, fid);
        Boolean success = false;
        if (integer == null) {
            success = userFriendMapper.addOrUpdateFriend(uid, fid, 0);
        } else if (integer.equals(notPass)) {
            success = userFriendMapper.addNewFriend(uid,fid);
        } else {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setMessage("你已经生或者对方已经是你的好友").setCode(90211));
        }

        if (!success) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setMessage("好友请求失败，请检查是否发送过请求").setCode(90211));
        }
    }

    void setMessage(RoomUsersDto roomUserDto, Integer uid) {
        List<UserDto> dtos = roomUserDto.getDtos();
        List<Integer> fids = dtos.stream().map(UserDto::getId).collect(Collectors.toList());
        fids.add(0);
        ResultVo<List<LastPrivateMessageDto>> lastPrivateMessage = chatClient.getLastPrivateMessage(fids, uid);
        if (lastPrivateMessage.getSucceed()) {
            List<LastPrivateMessageDto> data = lastPrivateMessage.getData();
            Map<Integer, String> map = new HashMap<>();
            data.stream().forEach(item -> {
                Integer id = item.getRid().equals(uid) ? item.getSid() : item.getRid();
                map.putIfAbsent(id, item.getMessage());
            });
            dtos.stream().forEach(item -> item.setMessage(map.get(item.getId())));
        } else {
            dtos.stream().forEach(item -> item.setMessage("没有消息记录"));
        }
    }

    MyPage<UserFriendVo> getUserInfo(List<UserFriend> list) {
        MyPage<UserFriendVo> myPage = new MyPage<>();
        if (list.size() == 0) {
            myPage.setContent(new LinkedList<UserFriendVo>());
            myPage.setTotalElements(0);
            return myPage;
        }
        List<Integer> uids = list.stream().map(UserFriend::getUser).collect(Collectors.toList());
        ResultVo<List<UserDto>> roomUserInfo = userClient.getRoomUserInfo(uids);
        if (!roomUserInfo.getSucceed()) {
            throw new CommonException(ResultCode.CUSTOM_FAIL.setMessage("查询用户失败"));
        }
        List<UserDto> data = roomUserInfo.getData();
        Map<Integer, String> userNames = data.stream().collect(
                Collectors.toMap(UserDto::getId, UserDto::getUserName));
        Map<Integer, String> avatars = data.stream().collect(
                Collectors.toMap(UserDto::getId, UserDto::getAvatar));
        List<UserFriendVo> ulist = new LinkedList<>();
        for (UserFriend userFriend : list) {
            UserFriendVo userFriendVo = new UserFriendVo();
            userFriendVo.setUser(userFriend.getUser());
            userFriendVo.setIsPass(userFriend.getIsPass());
            userFriendVo.setUserName(userNames.get(userFriend.getUser()));
            userFriendVo.setAvatar(avatars.get(userFriend.getUser()));
            ulist.add(userFriendVo);
        }
        myPage.setContent(ulist);
        return myPage;
    }
}
